package com.wy.tingshu.repository;

import com.wy.tingshu.data_object.AlbumDO;
import com.wy.tingshu.util.DBUtil;
import com.wy.tingshu.util.Log;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 *
 **/
public class AlbumRepo {
    //插入专辑
    @SneakyThrows
    public void insert(Integer uid, String title, String cover, int state) {
        try (Connection c= DBUtil.connection()){
            String sql="insert into albums(uid,title,cover,state)values(?,?,?,?)";
            try(PreparedStatement ps= c.prepareStatement(sql)){
                ps.setInt(1,uid);
                ps.setString(2,title);
                ps.setString(3,cover);
                ps.setInt(4, state);

                Log.println("执行SQL："+ps.toString());
                ps.executeUpdate();
            }
        }
    }

    //查询专辑
    @SneakyThrows
    public AlbumDO selectOneByUidAndAid(Integer uid, int aid) {
        String sql="select aid,uid,title,cover,state from albums where uid=? and aid=?";
        try (Connection c= DBUtil.connection()){
            try(PreparedStatement ps=c.prepareStatement(sql)){
                ps.setInt(1,uid);
                ps.setInt(2,aid);
                Log.println("执行SQLQ:"+ps);
                try(ResultSet rs= ps.executeQuery()){
                    if(!rs.next()){
                        return null;
                    }
                    return new AlbumDO(rs.getInt("aid"),rs.getInt("uid"),rs.getString("title"),rs.getString("cover"),rs.getInt("state"));
                }
            }

        }
    }

    //查询uid=?时所有专辑
    @SneakyThrows
    public List<AlbumDO> selectListByUid(int uid) {
        List<AlbumDO> list=new ArrayList<>();
        try (Connection c= DBUtil.connection()) {
            //通过uid展示当前用户的专辑列表
            String sql = "select aid,title,cover,state from albums where uid=? order by aid desc";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setInt(1, uid);
                Log.println("执行SQL:"+ps);
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        AlbumDO albumDO = new AlbumDO(
                                rs.getInt("aid"),
                                rs.getString("title"),
                                rs.getString("cover"),
                                rs.getInt("state")
                        );
                        list.add(albumDO);
                    }
                }
            }
        }
        return list;
    }
}
